//
//  AppDelegate.m
//  BGM
//
//  Created by liuqin on 2018/11/25.
//  Copyright © 2018年 com.alirtc.demo. All rights reserved.
//

#import "AppDelegate.h"

//VC
#import "HomeViewController.h"
#import "MessageViewController.h"
#import "PushViewController.h"
#import "ContactViewController.h"
#import "MeViewController.h"

#import "BaseTabBarViewController.h"


#import "MessageListViewController.h"
#import "MessageAcceptViewController.h"
#import "CommonViewController.h"

//login
#import "Common.h"
#import "LoginViewController.h"

#import <Contacts/Contacts.h>

#import <CoreLocation/CoreLocation.h>
#import "BGMHTTP.h"
#import "BGMuserFriendClass.h"
#import "BGMUser.h"
#import "BGMCity.h"
//#import "COSClient.h"
#import "RootViewController.h"

#import <AlipaySDK/AlipaySDK.h>
#import <NIMSDK/NIMSDK.h>
#import "ChatCustomDecoder.h"
#import <ShareSDK/ShareSDK.h>
#import <PushKit/PushKit.h>
#import "SVProgressHUD.h"
#import "GCQiniuUploadManager.h"

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

#define CC_SHA1_DIGEST_LENGTH   20          /* digest length in bytes */


@interface AppDelegate ()
<CLLocationManagerDelegate,
JPUSHRegisterDelegate,
NIMLoginManagerDelegate,
BGMPushViewDelegate,
PKPushRegistryDelegate>
{
    CLLocationManager *_locationManager;//定位服务管理类
    CLGeocoder * _geocoder;//初始化地理编码器
    
}

//@property (nonatomic, strong)UITabBarController *rootTabbar;

@property (nonatomic, strong)NSMutableArray *userFriendArray;

@property (nonatomic, assign)BOOL isLogin;
@property (nonatomic, assign)BOOL isJpush;


//七牛
@property (nonatomic, strong)NSString *scope;
@property (nonatomic, strong)NSString *accessKey;
@property (nonatomic, strong)NSString *secretKey;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.scope = @"banggemang";
    self.accessKey = @"5GOB9nk_uYdtSAnRPARLVuR9rVueTo2TsvEfIGK_";
    self.secretKey = @"Vyzv2Nps6qN-tBj_DRLhwQAYxwXrS6Q632gwJ66m";
    

    [self getFriendList];
   
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gotoHomeVC) name:@"gotoMainVC" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(gotoLoginVC) name:@"gotoLoginVC" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getAppFrinds) name:@"LoginSuccess" object:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hidePushView) name:@"HidenPushView" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showPushView) name:@"PUSHMESSAGE" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressBookDidChange:) name:CNContactStoreDidChangeNotification object:nil];
    
    [self registerIM];  //网易云

    //判断是不是第一次打开应用
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if(![ud objectForKey:@"isFristOpen"]){
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:@"1" forKey:@"isFristOpen"];//第一次打开
        [ud synchronize];
        RootViewController *vc = [[RootViewController alloc]init];
        vc.RootActionClickBlock = ^{
            [self gotoMainVC];
        };
        self.window.rootViewController = vc;
         [self.window makeKeyWindow];
    }else{
        
        [self gotoMainVC];
    }
    
    [self startLocating];  //定位
    [NIMCustomObject registerCustomDecoder:[[ChatCustomDecoder alloc]init]];
    
    [self resgisterJPpush:launchOptions]; //极光
    [self resgisterMobShareSDK];
    [self registerQiNiuToken];
    
    [self getUserInstrysList];
    [self getUserLable];

    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registrationAlia) name:@"registrationPJpush" object:nil];
    [self getBGMSet];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if([ud objectForKey:ISLOGINKEY]){
        NSString *key = [ud objectForKey:ISLOGINKEY];
        if ([key isEqualToString:@"1"]) {
            [self getFriendList];
        }
    }
 
}

//行业标签列表
- (void)getUserInstrysList{
    [BGMHTTP requestWithMethodName:@"login/getUserIndustrysList" parameters:@{@"key":@"values"} completion:^(BOOL success, NSError *error, NSDictionary *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            id userInstrys = [result objectForKey:@"data"];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:userInstrys forKey:@"userInstrys"];
            [userDefaults synchronize];
            
        });
    }];
}
//行业标签列表
- (void)getUserLable{
    [BGMHTTP requestWithMethodName:@"login/getUserLable" parameters:@{@"key":@"values"} completion:^(BOOL success, NSError *error, NSDictionary *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            id usertitle = [result objectForKey:@"data"];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:usertitle forKey:@"usertitle"];
            [userDefaults synchronize];
            
        });
        
    }];
}


#pragma mark 七牛
- (void)registerQiNiuToken {

    
    
    [[GCQiniuUploadManager sharedInstance] registerWithScope:self.scope
                                                   accessKey:self.accessKey
                                                   secretKey:self.secretKey];
    [[GCQiniuUploadManager sharedInstance] createToken];
    
}


#pragma mark 注册网易云信
- (void)registerIM{
    NSString *appKey = @"b170d1f8a89a04c9022e5066f05f73da";
    NIMSDKOption *option    = [NIMSDKOption optionWithAppKey:appKey];
    option.apnsCername = @"devePush";//devePush  proPush
    option.pkCername = @"pushKit";
    [[NIMSDK sharedSDK]registerWithOption:option];
    
    NIMServerSetting *setting    = [[NIMServerSetting alloc] init];
    setting.httpsEnabled = NO;
    [[NIMSDK sharedSDK] setServerSetting:setting];
   
    UIUserNotificationSettings *userNotifiSetting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:userNotifiSetting];
    
    PKPushRegistry *pushRegistry = [[PKPushRegistry alloc] initWithQueue:nil];
    pushRegistry.delegate = self;
    pushRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
   

}
    
    

//云信登录成功回调。。
-(void)onLogin:(NIMLoginStep)step{
    
    if (step == NIMLoginStepLoginOK) {
        NSLog(@"--------->网易云信自动登录成功<-----------");
    }
    
}

-(void)onAutoLoginFailed:(NSError *)error{
    NSLog(@"--------->网易云信自动登录失败<-----------");

}
#pragma mark 注册极光
-(void)resgisterJPpush:(NSDictionary *)launchOptions{
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
     
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    [JPUSHService setupWithOption:launchOptions appKey:@"e83fdd6581c0653ccf752e40" channel:@"" apsForProduction:NO];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.isJpush = YES;
                [[NSNotificationCenter defaultCenter]postNotificationName:@"registrationPJpush" object:nil];
            });
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    
    
    
}
- (void)resgisterMobShareSDK{
    [ShareSDK registPlatforms:^(SSDKRegister *platformsRegister) {
        [platformsRegister setupWeChatWithAppId:@"wxf5a1349b6a43c466" appSecret:@"f89dc10ecadebfb4712fbe6923530193"];
//        [platformsRegister setupSinaWeiboWithAppkey:@"" appSecret:@"" redirectUrl:@""];
    }];
}


#pragma mark 进入主页
- (void)gotoHomeVC{
    
    
    self.isLogin = YES;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"registrationPJpush" object:nil];
    [self performSelector:@selector(getBGMFriends) withObject:nil afterDelay:5];

    //读取沙盒数据
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSDictionary *userDic = [ud objectForKey:usermessage];
    BGMUser *user = [BGMUser shareInstance];
    user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
    user.imToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"imToken"]];
    user.userToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"token"]];

    NSString *account = user.userId;
    NSString *token   = user.imToken;
    [[[NIMSDK sharedSDK]loginManager]addDelegate:self];
     [self getType];  //获取发布类型
    
    NIMAutoLoginData *loginData = [[NIMAutoLoginData alloc] init];
    loginData.account = account;
    loginData.token = token;    
    [[[NIMSDK sharedSDK] loginManager] autoLogin:loginData];
//    [self rootMainViewController];
    
    self.rootTabbar = [[BaseTabBarViewController alloc]init];
    self.window.rootViewController = self.rootTabbar;
    
    
    self.pushView = [[BGMPushView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    self.pushView.pushViewDelegate = self;
    [self.window addSubview:self.pushView];
    self.pushView.hidden = YES;
    [self.window makeKeyWindow];
  
}
#pragma mark 发布类型
- (void)getType{
    NSDictionary *dic = @{@"userToken":[BGMUser shareInstance].userToken};
    [BGMHTTP requestWithMethodName:@"publish/getPublishType" parameters:dic completion:^(BOOL success, NSError *error, NSDictionary *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
            if ([code isEqualToString:@"200"]) {
                NSArray *array = [result objectForKey:@"data"];
                NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
                [ud setObject:array forKey:@"PUSHTYPE"];
                [ud synchronize];
                [self.pushView getTypeArray:array];
            }
        });
    }];
    
}
- (void)hidePushView{
    [self clickPushBgView];
}
-(void)clickPushBgView{
    self.pushView.hidden = YES;
}
- (void)showPushView{
    self.pushView.hidden = NO;
    [self.window bringSubviewToFront:self.pushView];
    [self.pushView showPushView];

    
}
- (void)rootMainViewController{
//    self.rootTabbar = [[UITabBarController alloc]init];
//    [[UITabBar appearance] setBackgroundColor:[UIColor whiteColor]];
//    [[UITabBar appearance] setShadowImage:[UIImage new]];
//    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc]init]];
//
//    HomeViewController *homeVC = [[HomeViewController alloc]init];
//    MessageViewController *secVC = [[MessageViewController alloc]init];
//    PushViewController *thrVC = [[PushViewController alloc]init];
//    ContactViewController *fourVC = [[ContactViewController alloc]init];
//    MeViewController *fiveVC = [[MeViewController alloc]init];
//    NSArray *vcs = @[homeVC,secVC,thrVC,fourVC,fiveVC];
//    NSMutableArray *ncArr = [[NSMutableArray alloc]init];
//    for(int i = 0;i<vcs.count;i++){
//        UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:[vcs objectAtIndex:i]];
//        UIImage *normalImage = [UIImage imageNamed:[NSString stringWithFormat:@"tabbar_%d",i]];
//        UIImage *seleImage = [UIImage imageNamed:[NSString stringWithFormat:@"tabbar_%d_sele",i]];
//        normalImage = [normalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        seleImage = [seleImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        nc.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"" image:normalImage selectedImage:seleImage];
//        [ncArr addObject:nc];
//    }
//    self.rootTabbar.viewControllers = ncArr;
//    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor clearColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
//
//    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor clearColor],NSForegroundColorAttributeName, nil]forState:UIControlStateSelected];
//    self.window.rootViewController = self.rootTabbar;
//    [self.window makeKeyWindow];
}


#pragma mark 进入登录页面
- (void)gotoLoginVC{
    
    self.isLogin = NO;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"registrationPJpush" object:nil];
    
    LoginViewController *vc = [[LoginViewController alloc]init];
    UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc];
    nc.navigationBar.hidden = YES;
    self.window.rootViewController = nc;
    [self.window makeKeyWindow];
}
-(void)startLocating{
    
    if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许
        
        _locationManager = [[CLLocationManager alloc] init];
        
        _locationManager.delegate = self;//遵循代理
        
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        _locationManager.distanceFilter = 10.0f;
        
        [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8以上版本定位需要）
        
        [_locationManager startUpdatingLocation];//开始定位
        
    }else{//不能定位用户的位置的情况再次进行判断，并给与用户提示
        //1.提醒用户检查当前的网络状况
        //2.提醒用户打开定位开关
        BGMCity *bgCity = [BGMCity shareInstance];
        bgCity.city = @"杭州";
    }
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //当前所在城市的坐标值
    CLLocation *currLocation = [locations lastObject];
    //根据经纬度反向地理编译出地址信息
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            NSDictionary *address = [placemark addressDictionary];
            NSString *city = [address objectForKey:@"City"];
            BGMCity *bgCity = [BGMCity shareInstance];
            bgCity.city = city;
        }
        
    }];
    
}



/* 定位失败后 回调 */
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    if (error.code == kCLErrorDenied) {
        // 提示用户出错
    }
}


-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
//    NSLog(@"asdfasfsa");
}

- (void)gotoMainVC{
    //判断用户是否已经登录
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if([ud objectForKey:ISLOGINKEY]){
        NSString *key = [ud objectForKey:ISLOGINKEY];
        if ([key isEqualToString:@"1"]) {
            [self gotoHomeVC];
        }else{
            [self gotoLoginVC];
        }
    }else{
        [self gotoLoginVC];
    }
}
#pragma mark 通讯录
- (void)getFriendList{
    
    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {//判断是否授权
        [self openContact];
    }else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined){ //尚未选择了一个关于是否应用程序可以访问联系人数据
        [self openContact];
    }else{
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"0" forKey:@"isOpenContactStore"];
        [userDefaults synchronize];
        [BGMUser shareInstance].isOpenContactStore = @"0";
 
    }
}

- (void)openContact{
    CNContactStore *store = [[CNContactStore alloc] init];
    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) { //授权成功
            [self setFriends];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:@"1" forKey:@"isOpenContactStore"];
            [userDefaults synchronize];
            [BGMUser shareInstance].isOpenContactStore = @"1";
            
        }else{
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:@"0" forKey:@"isOpenContactStore"];
            [userDefaults synchronize];
            [BGMUser shareInstance].isOpenContactStore = @"0";

            
        }
        
    }];
}

- (void)setFriends{
    
 
    self.userFriendArray = [[NSMutableArray alloc]init];
    CNContactStore *store = [[CNContactStore alloc]init];
    NSArray *keys = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey];
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
    BOOL b = [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        BGMuserFriendClass *friend = [[BGMuserFriendClass alloc]init];
        NSString *givenName = contact.givenName;
        NSString *familyName = contact.familyName;
        NSString *str = [NSString stringWithFormat:@"%@%@",familyName,givenName];
        friend.name = str;
        NSArray *phoneArray = contact.phoneNumbers;
        if (phoneArray.count>0) {
            CNLabeledValue *labelValue = [phoneArray objectAtIndex:0];
            CNPhoneNumber *number = labelValue.value;
            NSString *str =number.stringValue;

            NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:

                                                      @"[^0-9]+" options:0 error:nil];

            str  = [regularExpression stringByReplacingMatchesInString:str options:0 range:NSMakeRange(0, str.length) withTemplate:@""];
            str = [str stringByReplacingOccurrencesOfString:@"-" withString:@""];
            str = [str stringByReplacingOccurrencesOfString:@"+86" withString:@""];
            friend.userNumber = str;
        }
        if(phoneArray.count>0){
            [self.userFriendArray addObject:friend];
            [BGMUser shareInstance].userFriendArray = self.userFriendArray;
        }
    }];
    
    if (b) {
         [self getBGMFriends];
    }else{
        NSLog(@"asdfasfsafasfasfsaf");
    }
   
    
}

- (void)getBGMFriends{
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if([ud objectForKey:ISLOGINKEY]){
        NSString *key = [ud objectForKey:ISLOGINKEY];
        if ([key isEqualToString:@"1"]) {
            [self getAppFrinds];
        }
    }
}

- (void)getAppFrinds{
    
    NSArray *array = [BGMUser shareInstance].userFriendArray;
    if(array.count >0 ){
        NSMutableArray *resultArray = [[NSMutableArray alloc]init];
        for (BGMuserFriendClass *user in array) {
            if (user !=nil) {
                NSDictionary *dic = @{@"name":user.name,@"number":user.userNumber};
                [resultArray addObject:dic];
            }
        }
        NSData *data=[NSJSONSerialization dataWithJSONObject:resultArray options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        NSUserDefaults *ud1 = [NSUserDefaults standardUserDefaults];
        NSDictionary *userDic1 = [ud1 objectForKey:usermessage];
        BGMUser *user = [BGMUser shareInstance];
        user.userId = [NSString stringWithFormat:@"%@",[userDic1 objectForKey:@"usersId"]];
        user.imToken = [NSString stringWithFormat:@"%@",[userDic1 objectForKey:@"imToken"]];
        user.userToken = [NSString stringWithFormat:@"%@",[userDic1 objectForKey:@"token"]];
        
        NSString *userToken = [BGMUser shareInstance].userToken;
        NSString *userId = [BGMUser shareInstance].userId;

        NSDictionary *params = @{@"userToken":userToken,@"userId":userId,@"jsonStr":jsonStr};
        [BGMHTTP requestWithMethodName:@"contacts/synchronizationContacts" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
            NSLog(@"向后台同步通训录");
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:@"getHomeMessage" object:nil];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"freshContactViewController" object:nil];

                [self getAppUsers];
            });
        }];
    }
}
//app已经用户好友  app不给谁看
- (void)getAppUsers{
    [self getContactsList];
#pragma mark 未完成2019春节弄
    [self getAppNowSee];
  
}
- (void)getContactsList{
    NSDictionary *params = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId};
    [BGMHTTP requestWithMethodName:@"contacts/getContactsList" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if([code isEqualToString:@"200"]){
             NSArray *array = [result objectForKey:@"data"];
            NSMutableArray *resultAPP = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in array) {
                BGMuserFriendClass *friend = [[BGMuserFriendClass alloc]init];
                friend.creatTime = [NSString stringWithFormat:@"%@",[dic objectForKey:@"creatTime"]];
                friend.headImage = [NSString stringWithFormat:@"%@",[dic objectForKey:@"headImage"]];
                friend.friendId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]]; //唯一
                friend.name = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
                friend.spareOne = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareOne"]];
                friend.spareTwo = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spareTwo"]];
                friend.type = [NSString stringWithFormat:@"%@",[dic objectForKey:@"type"]];
                friend.userId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userId"]];
                friend.isInvite = @"0";
                if([friend.type isEqualToString:@"1"]){
                    [resultAPP addObject:dic];
                }
            }
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:resultAPP forKey:@"appFriend"];
            [userDefaults synchronize];
            
         }else{
         }
    }];
}
- (void)getAppNowSee{
  
}


-(void)addressBookDidChange:(NSNotification*)notification{
    // 比如上传
   
    //判断用户是否已经登录
   

}

//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//  sourceApplication:(NSString *)sourceApplication
//         annotation:(id)annotation {
//
//    if ([url.host isEqualToString:@"safepay"]) {
//        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//    }
//    return YES;
//}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"AliPaySuccess" object:resultDic];
        }];
        
        
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            
        }];
    }
    
    
    
    
    return YES;
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

#pragma mark 注册推送
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    //云信
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken];
    
    
//    NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""]                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
//
//    NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
//    //获取终端设备标识，这个标识需要通过接口发送到服务器端，服务器端推送消息到APNS时需要知道终端的标识，APNS通过注册的终端标识找到终端设备
//    NSLog(@"%@",token);
}
///云信
- (void)onReceiveCustomSystemNotification:(NIMCustomSystemNotification *)notification{
    NSLog(@"asdfsafsfa");
}
    
    

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];   //信息处理
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
#pragma mark 收到推送 查看信息
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
            if([userInfo objectForKey:@"nim"]){  //网易云信通知
                UIApplication *app = [UIApplication sharedApplication];
                UIWindow *keyWindow = app.keyWindow;
                BaseTabBarViewController *tabBar = (BaseTabBarViewController *)keyWindow.rootViewController;
                [tabBar selectedItemTabBarIndex:1];
            }
            else
            {  //极光
                [self getJPushDealWith:userInfo];
            }
        } else {
            
        }
    }
    completionHandler();  // 系统要求执行这个方法
}
- (void)getJPushDealWith:(NSDictionary *)dic{
    
    UIApplication *app = [UIApplication sharedApplication];
    UIWindow *keyWindow = app.keyWindow;
    BaseTabBarViewController *tabBar = (BaseTabBarViewController *)keyWindow.rootViewController;
    [tabBar selectedItemTabBarIndex:1];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if([ud objectForKey:ISLOGINKEY]){
        NSString *key = [ud objectForKey:ISLOGINKEY];
        if (![key isEqualToString:@"1"]) {
            return;
        }
    }
    
 
    //读取沙盒数据
    NSDictionary *userDic = [ud objectForKey:usermessage];
    BGMUser *user = [BGMUser shareInstance];
    user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
    user.imToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"imToken"]];
    user.userToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"token"]];
    
    
    UINavigationController *nc = [tabBar.viewControllers objectAtIndex:1];
    MessageListViewController *vclist = [[MessageListViewController alloc]init];
    
    NSString *bigTypeKey= [NSString stringWithFormat:@"%@",[dic objectForKey:@"bigTypeKey"]];
    if ([bigTypeKey isEqualToString:@"PUBLISH_MESSAGE"]) {
        vclist.maeesgeType = 1;
    }else if ([bigTypeKey isEqualToString:@"SYSTEM_MESSAGE"]){
        vclist.maeesgeType = 2;
    }else if([bigTypeKey isEqualToString:@"THANK_MESSAGE"]){
        vclist.maeesgeType = 3;
    }
    [nc pushViewController:vclist animated:YES];
    
    NSString *type= [NSString stringWithFormat:@"%@",[dic objectForKey:@"pushType"]];
    if ([type isEqualToString:@"notice_of_action"]) {  //受理
        MessageAcceptViewController *accVc = [[MessageAcceptViewController alloc]init];
        accVc.pushMessageId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"pushId"]];
        [vclist.navigationController pushViewController:accVc animated:YES];
    }else if ([type isEqualToString:@"comment"]){
        CommonViewController *vc = [[CommonViewController alloc]init];
        vc.publishId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"pushId"]];//发布id
        vc.userId = [BGMUser shareInstance].userId;////////
        vc.publishHelpUserId = @"";
        [vclist.navigationController pushViewController:vc animated:YES];
        
    }

    
}


- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type{
    
//    NSString *str = [NSString stringWithFormat:@"%@",credentials.token];
//    _tokenStr = [[[str stringByReplacingOccurrencesOfString:@"<" withString:@""]
//                  stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    [application registerForRemoteNotifications];//必须先实现这个方法，才会走下面的方法
}



- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type {
    
    NSLog(@"asdfsfsaf");
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pancal) name:@"precancel" object:nil];
//    NSDictionary *dic = [self jsonToDictionary:[[payload.dictionaryPayload objectForKey:@"aps"] objectForKey:@"alert"]];
//    if ([[dic objectForKey:@"cmd"] isEqualToString:@"precall"]) {
//        UIUserNotificationType theType = [UIApplication sharedApplication].currentUserNotificationSettings.types;
//        if (theType == UIUserNotificationTypeNone)
//        {
//            UIUserNotificationSettings *userNotifySetting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
//            [[UIApplication sharedApplication] registerUserNotificationSettings:userNotifySetting];
//        }
//        UILocalNotification *backgroudMsg = [[UILocalNotification alloc] init];
//        if (backgroudMsg) {
//            backgroudMsg.timeZone = [NSTimeZone defaultTimeZone];
//            backgroudMsg.alertBody = @"门口机来电";
//            backgroudMsg.alertAction = @"查看";
//            //设置通知的相关信息，这个很重要，可以添加一些标记性内容，方便以后区分和获取通知的信息
//            NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];;
//            backgroudMsg.userInfo = infoDic;
//            [[UIApplication sharedApplication] presentLocalNotificationNow:backgroudMsg];
//            [self cerateAVAudioPlayer];
//        }
//    }else if ([[dic objectForKey:@"cmd"] isEqualToString:@"precancel"]){
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"precancel"
//                                                            object:nil];
//        [self pancalStopSound];
//    }
    
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}








-(void)registrationAlia{
    if (self.isLogin && self.isJpush) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        NSDictionary *userDic = [ud objectForKey:usermessage];
        BGMUser *user = [BGMUser shareInstance];
        user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
        
        [JPUSHService setAlias:user.userId completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"JPAlias 注册成功 =%@",iAlias);
        } seq:1];
    }else{
        [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"JPAlias退出");
        } seq:1];
    }
    
   
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
 }
#pragma mark 上线要改
-(void)getBGMSet{
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",Server_url,@"index/getOpens"];
    NSURL *url = [NSURL URLWithString:urlStr];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *data = [dict objectForKey:@"data"];
                NSString *open = [NSString stringWithFormat:@"%@",[data objectForKey:@"open"]];
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:open forKey:@"openSet"];
//                [userDefaults setObject:@"YES" forKey:@"openSet"]; //

                [userDefaults synchronize];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:@"NO" forKey:@"openSet"];
                [userDefaults synchronize];
            });
        }
        
    }];
    //7.执行任务
    [dataTask resume];
    
}
@end
